<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EduSchoolContactApi } from '#/api/edu/base/schoolContact';

import { ref, watch } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { $t } from '#/locales';

import { useContactGridColumns } from '../data';
import Form from './contact-form.vue';

const props = defineProps<{
  schoolContacts: EduSchoolContactApi.SchoolContact[];
}>();
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});
const contactList = ref<EduSchoolContactApi.SchoolContact[]>([]);
const index = ref<number>(0);
/** 刷新表格 */
function handleRefresh(data: EduSchoolContactApi.SchoolContact) {
  if (data.id) {
    contactList.value = contactList.value.map((item) =>
      item.id === data.id ? data : item,
    );
  } else {
    index.value = index.value - 1;
    data.id = index.value;
    contactList.value.push(data);
  }
  gridApi.setGridOptions({ data: contactList.value });
}

/** 创建学校联系人 */
function handleCreate() {
  formModalApi.setData({ schoolId: props.school.id }).open();
}

/** 编辑学校联系人 */
function handleEdit(row: EduSchoolContactApi.SchoolContact) {
  formModalApi.setData(row).open();
}

/** 删除学校联系人 */
async function handleDelete(row: EduSchoolContactApi.SchoolContact) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.contactName]),
    duration: 0,
  });
  try {
    contactList.value = contactList.value.filter((item) => item.id !== row.id);
    gridApi.setGridOptions({ data: contactList.value });
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.contactName]),
    });
  } finally {
    hideLoading();
  }
}

/** 批量删除学校联系人 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    // 根据checkedIds 删除contactList中对应的项
    contactList.value = contactList.value.filter(
      (item) => !checkedIds.value.includes(item.id!),
    );
    gridApi.setGridOptions({ data: contactList.value });
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: EduSchoolContactApi.SchoolContact[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    id: 'schoolContact-grid-school',
    columns: useContactGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: false,
    },
    keepSource: true,
    data: [] as EduSchoolContactApi.SchoolContact[],
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<EduSchoolContactApi.SchoolContact>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
watch(
  () => props.schoolContacts,
  (newValue) => {
    // 如果已经是数组，直接使用；如果是字符串，解析后使用
    const data = Array.isArray(newValue)
      ? newValue
      : JSON.parse(newValue || '[]');

    data.forEach((item) => {
      if (!item.id) {
        index.value = index.value - 1;
        item.id = index.value;
      }
    });
    contactList.value = data;
    gridApi.setGridOptions({ data });
  },
  { immediate: true },
);
/** 暴露出表单校验方法和表单值获取方法 */
defineExpose({
  getValues: () => contactList.value,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <Grid table-title="学校联系人列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['学校联系人']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['edu:base:school-contact:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.deleteBatch'),
              type: 'primary',
              danger: true,
              icon: ACTION_ICON.DELETE,
              disabled: isEmpty(checkedIds),
              auth: ['edu:base:school-contact:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['edu:base:school-contact:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['edu:base:school-contact:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
